#!/data/data/com.termux/files/usr/bin/bash
#set -x

remote_dir=/volume1/entertainment/document/todo
local_dir=/data/data/com.termux/files/home/sdcard/Android/data/nl.mpcjanssen.simpletask/files
host=admin@10.189.34.197
function gen_filelists()
{
    ssh ${host} "cd ${remote_dir}; stat -c '%n %Y' *" > ${local_dir}/.rfiles
    cd ${local_dir}
    stat -c '%n %Y' * > ./.lfiles

    awk '{print $1}' ./.lfiles | sort > ./.tlfilelists
    awk '{print $1}' ./.rfiles | sort > ./.trfilelists
    comm -23 ./.tlfilelists ./.trfilelists > ./.lfilelists
    comm -13 ./.tlfilelists ./.trfilelists > ./.rfilelists
    comm -12 ./.tlfilelists ./.trfilelists > ./.tcfilelists

    cat ./.tcfilelists | while read filename
    do
        cat ./.lfiles | while read lfile ltime
        do
            if [ "${filename}" == "${lfile}" ]
            then
                cat ./.rfiles | while read rfile rtime
                do
                    if [ "${filename}" == "${rfile}" ]
                    then
                        if [ ${ltime} -gt ${rtime} ]
                        then
                            echo "${filename}" >> ./.lfilelists
                        else
                            echo "${filename}" >> ./.rfilelists
                        fi
                        break
                    fi
                done
                break
            fi
        done
    done
}

cd ${local_dir}
echo -n > ./.lfilelists
echo -n > ./.rfilelists
gen_filelists

#rsync -av admin@192.168.0.2::todo/ /data/data/com.termux/files/home/sdcard/Android/data/nl.mpcjanssen.simpletask/files/ > /data/data/com.termux/files/home/.shortcuts/tasks/.pull.txt 2>&1

cp ./todo.txt ./.todo.txt.old
rsync -av --include-from=.rfilelists --exclude="*" ${host}::todo/ ${local_dir}/ > /data/data/com.termux/files/home/.shortcuts/tasks/.sync.txt 2>&1
echo "======================" >> /data/data/com.termux/files/home/.shortcuts/tasks/.sync.txt
rsync -av --include-from=.lfilelists --exclude="*" ${local_dir}/ ${host}::todo/ >> /data/data/com.termux/files/home/.shortcuts/tasks/.sync.txt 2>&1
cp ./todo.txt ./.todo.txt.bak
termux-dialog confirm -t "OUTPUT" -i "$(cat /data/data/com.termux/files/home/.shortcuts/tasks/.sync.txt)"
#set +x
